package com.cherry.androidviewdemo.widget

import android.content.Context
import android.graphics.*
import android.util.AttributeSet
import android.view.View
import kotlin.math.min
import kotlin.math.sqrt

/**
 * @author DongMS
 * @since 2020/6/4
 */

class ShapeView @JvmOverloads constructor(context: Context, attributeSet: AttributeSet? = null, defStyleAttr: Int = 0) : View(context, attributeSet, defStyleAttr) {

    private val circlePaint: Paint
    private val rectPaint: Paint
    private val trianglePaint: Paint

    var circleColor = Color.RED
    var rectColor = Color.YELLOW
    var triangleColor = Color.BLUE

    var shape = Shape.CIRCLE
        set(value) {
            field = value
            invalidate()
        }

    private val rect = Rect()

    private val trianglePath = Path()

    init {
        circlePaint = initPaint(circleColor)
        rectPaint = initPaint(rectColor)
        trianglePaint = initPaint(triangleColor)

    }

    private fun initPaint(solidColor: Int): Paint {
        return Paint(Paint.ANTI_ALIAS_FLAG or Paint.DITHER_FLAG).apply {
            color = solidColor
        }
    }

    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec)
        //确保是个正方形
        val width = MeasureSpec.getSize(widthMeasureSpec)
        val height = MeasureSpec.getSize(heightMeasureSpec)
        val size = min(width, height)
        setMeasuredDimension(size, size)
    }

    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)
        val width = width
        val height = height
        val center = width / 2f
        when (shape) {
            Shape.CIRCLE -> {
                canvas.drawCircle(center, center, center, circlePaint)
            }
            Shape.RECT -> {
                rect.set(0, 0, width, height)
                canvas.drawRect(rect, rectPaint)
            }
            Shape.TRIANGLE -> {
                //等边三角形tan60°=根号3
                trianglePath.moveTo(center, 0f)
                trianglePath.lineTo(0f, sqrt(3f) * center)
                trianglePath.lineTo(width.toFloat(), sqrt(3f) * center)
                trianglePath.close()
                canvas.drawPath(trianglePath, trianglePaint)
            }
        }
    }

    fun changeShape() {
        shape = when (shape) {
            Shape.CIRCLE -> Shape.RECT
            Shape.RECT -> Shape.TRIANGLE
            Shape.TRIANGLE -> Shape.CIRCLE
        }
    }

    enum class Shape {
        CIRCLE, RECT, TRIANGLE
    }

}